package com.sfj.common.util;


import com.kaka.starter.token.util.HeaderUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @Date 2025/04/30
 */
public class MySqlHeadBuild {
    public static void addEntityBuild(Object target) {
        setIfExists(target, FormDefaultColumnEnum.TENANTID.getCode(), HeaderUtils.getTenantId());
        setIfExists(target, FormDefaultColumnEnum.CREATEUSER.getCode(), HeaderUtils.getUserId());
        setIfExists(target, FormDefaultColumnEnum.GROUPIDS.getCode(), HeaderUtils.getQueryGroups());
        setIfExists(target, FormDefaultColumnEnum.CREATETIME.getCode(), LocalDateTime.now().withNano(0));
        //todo 先写死 后续在创建sql的时候根据长度和默认值来控制
        setIfExists(target, FormDefaultColumnEnum.DELTAG.getCode(), "0");
    }

    //todo update dto 需要加上这两个字段
    public static void updateEntityBuild(Object target) {
        setIfExists(target, FormDefaultColumnEnum.UPDATETIME.getCode(), LocalDateTime.now().withNano(0));
        setIfExists(target, FormDefaultColumnEnum.UPDATEUSER.getCode(), HeaderUtils.getUserId());
    }

    //todo 先默认加一个 应该根据条件配置 如数据权限
    public static void queryEntityBuild(Object target) {
        setIfExists(target, FormDefaultColumnEnum.TENANTID.getCode(), HeaderUtils.getTenantId());
    }

    private static void setIfExists(Object target, String fieldName, Object value) {
        try {
            Field field = getField(target.getClass(), CamelCaseUtil.underlineToCamelSafe(fieldName));
            if (field != null) {
                field.setAccessible(true);
                if (value instanceof Collection) {
                    String joined = ((Collection<?>) value)
                            .stream()
                            .map(Object::toString)
                            .collect(Collectors.joining(","));
                    field.set(target, joined);
                } else {
                    field.set(target, value);
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("无法设置字段：" + fieldName, e);
        }
    }

    // 递归查找父类字段
    private static Field getField(Class<?> clazz, String fieldName) {
        while (clazz != null) {
            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return null;
    }
}
